package com.dfbz.bigdata.modules.system.miniapp.service;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dfbz.bigdata.common.utils.R;
import com.dfbz.bigdata.modules.system.miniapp.domain.UserDesignerandpersonal;
import com.dfbz.bigdata.modules.system.miniapp.domain.WXAuth;
import com.dfbz.bigdata.modules.system.miniapp.domain.WxUserInfo;
import com.dfbz.bigdata.modules.system.miniapp.dto.UserDto;
import com.dfbz.bigdata.modules.system.miniapp.mapper.UserDesignerandpersonalMapper;
import com.dfbz.bigdata.modules.system.miniapp.utils.JWTUtils;
import com.dfbz.bigdata.modules.system.miniapp.utils.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private WxService wxService;

    @Autowired
    private UserDesignerandpersonalMapper userMapper;

    @Value("${wxmini.secret}")
    private String secret;
    @Value("${wxmini.appid}")
    private String appid;

    public String getSessionId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        url = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);

//        res里是session_key 和 openid
        String res = HttpUtil.get(url);

        String sessionId = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set(RedisKey.WX_SESSION_ID + sessionId, res,3, TimeUnit.MINUTES);
        return sessionId;
    }


    public R<UserDto> authLogin(WXAuth wxAuth){

        try {
//            通过 encryptedData  sessionid iv 得到用户信息json
            String wxRes = wxService.wxDecrypt(wxAuth.getEncryptedData(), wxAuth.getSessionId(), wxAuth.getIv());
//            解析json 变成对应实体 WxUserInfo
            WxUserInfo wxUserInfo = JSON.parseObject(wxRes,WxUserInfo.class);
            System.out.println("解谜后的信息-------------------------------------");
            System.out.println(wxUserInfo);

//            得到openId判断是否数据库里存在  存在就登录 不存在先注册在登录
            String openId = wxAuth.getOpenId();
            LambdaQueryWrapper<UserDesignerandpersonal> lqw=new LambdaQueryWrapper<>();
            lqw.eq(UserDesignerandpersonal::getOpenId,openId);
            UserDesignerandpersonal user = userMapper.selectOne(lqw);
            if(user!=null){
//                登录成功
                UserDto userDto = new UserDto();
                BeanUtils.copyProperties(user,userDto);
                return this.login(userDto);
            } else {
                UserDto userDto = new UserDto();
                userDto.from(wxUserInfo);
                userDto.setOpenId(openId);
                return this.register(userDto);
            }



        } catch (Exception e) {
            e.printStackTrace();
        }

        return R.error("登录失败");

    }

    public R<UserDto> login(UserDto userDto) {

        String token = JWTUtils.sign(userDto.getUserId());
        userDto.setToken(token);
        //保存到redis内,下次就直接跳过验证
        redisTemplate.opsForValue().set(RedisKey.TOKEN_KEY + token, JSON.toJSONString(userDto), 7, TimeUnit.DAYS);
        return R.success(userDto);
    }

    public  R<UserDto> register(UserDto userDto) {
        UserDesignerandpersonal user = new UserDesignerandpersonal();
        BeanUtils.copyProperties(userDto,user);
        user.setUserLabel("普通用户");
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insert(user);
        //已存在直接登录
        return this.login(userDto);
    }

}
